//
//  QSRouter.swift
//  TestSwift
//
//  Created by Song on 2018/5/21.
//  Copyright © 2018 Song. All rights reserved.
//

import UIKit

/** 路由字典参数 */
private let qs_fromVcClass = "fromVcClass"      // 从哪个控制器跳转，AnyClass类型

class QSRouter: NSObject {
    /// 跳转到tabBarController中的某个tab
    ///
    /// - Parameter index: 下标
    class func qs_openTabIndex(_ index: Int) {
        // 当前控制器
        if let currentVc = self.qs_getCurrentViewController() {
            if let nav = currentVc.navigationController {
                nav.popToRootViewController(animated: false)
            }
        }
        
        // 获取tabBarViewController
        if let rootViewController = UIApplication.shared.keyWindow?.rootViewController {
            if (rootViewController.isKind(of: UITabBarController.self)) {
                let tabBarController = rootViewController as! UITabBarController
                
                tabBarController.selectedIndex = index
            }
        }
    }
    
    /**
     *  界面跳转
     *
     *  @param vc 要跳转过去的控制器
     *  @param routerParmsDict 跳转时携带的参数字典
     *  @param isPresent 是否present
     *  @param isAnimated 跳转时是否需要动画
     *  @param isReuse 是否复用已存在的控制器
     *  @param presentComplete present跳转完成后回调
     */
    class func qs_open(_ vc: AnyClass, routerParmsDict: Dictionary<String, Any>?, isPresent: Bool = false, isAnimated: Bool = true, isReuse: Bool = false, presentComplete: (()->Void)? = nil) {
        if let cls = vc as? QSRoutable.Type {
            // 当前控制器
            if let currentVc = self.qs_getCurrentViewController() {
                var parasDict = Dictionary<String, Any>.init()
                if routerParmsDict != nil {
                    parasDict = routerParmsDict!
                }
                parasDict["fromVcClass"] = currentVc.classForCoder
                
                // 要跳转过去的控制器
                let toVc = cls.qs_initWithParmsDict!(parasDict)
                toVc.hidesBottomBarWhenPushed = true
                
                if currentVc.navigationController != nil && !isPresent {
                    // 如果控制器存在且进行复用
                    if isReuse {
                        var hasReuseVc: Bool = true
                        
                        for reuseVc in (currentVc.navigationController?.children)! {
                            if reuseVc.classForCoder == cls {
                                if let reVc = reuseVc as? QSRoutable {
                                    
                                    if let _ = reVc.qs_updateParmsDict?(parasDict) {}
                                }
                                currentVc.navigationController?.popToViewController(reuseVc, animated: isAnimated)
                                
                                hasReuseVc = true
                                break
                            } else {
                                hasReuseVc = false
                            }
                        }
                        
                        if !hasReuseVc {
                            currentVc.navigationController?.pushViewController(toVc, animated: isAnimated)
                        }
                    } else {
                        currentVc.navigationController?.pushViewController(toVc, animated: isAnimated)
                    }
                } else {
                    currentVc.present(toVc, animated: isAnimated, completion: presentComplete)
                }
            }
        }
    }
    
    /**
     *  界面跳转
     *
     *  @param vc 要跳转过去的控制器
     *  @param routerParmsModel 跳转时携带的参数字典
     *  @param isPresent 是否present
     *  @param isAnimated 跳转时是否需要动画
     *  @param isReuse 是否复用已存在的控制器
     *  @param presentComplete present跳转完成后回调
     */
    class func qs_open(_ vc: AnyClass, routerParmsModel: QSBaseRouterModel?, isPresent: Bool = false, isAnimated: Bool = true, isReuse: Bool = false, presentComplete: (()->Void)? = nil) {
        if let cls = vc as? QSRoutable.Type {
            // 当前控制器
            if let currentVc = self.qs_getCurrentViewController() {
                var parasModel = QSBaseRouterModel.init()
                if routerParmsModel != nil {
                    parasModel = routerParmsModel!
                }
                parasModel.fromVcClass = currentVc.classForCoder
                
                // 要跳转过去的控制器
                let toVc = cls.qs_initWithParmsModel!(parasModel)
                toVc.hidesBottomBarWhenPushed = true
                
                if currentVc.navigationController != nil && !isPresent {
                    // 如果控制器存在且进行复用
                    if isReuse {
                        var hasReuseVc: Bool = true
                        
                        for reuseVc in (currentVc.navigationController?.children)! {
                            if reuseVc.classForCoder == cls {
                                if let reVc = reuseVc as? QSRoutable {
                                    
                                    if let _ = reVc.qs_updateParmsModel?(parasModel) {}
                                }
                                currentVc.navigationController?.popToViewController(reuseVc, animated: isAnimated)
                                
                                hasReuseVc = true
                                break
                            } else {
                                hasReuseVc = false
                            }
                        }
                        
                        if !hasReuseVc {
                            currentVc.navigationController?.pushViewController(toVc, animated: isAnimated)
                        }
                    } else {
                        currentVc.navigationController?.pushViewController(toVc, animated: isAnimated)
                    }
                } else {
                    currentVc.present(toVc, animated: isAnimated, completion: presentComplete)
                }
            }
        }
    }
    
    /**
     *  获取当前页面
     */
    private class func qs_getCurrentViewController() -> UIViewController? {
        if let rootViewController = UIApplication.shared.keyWindow?.rootViewController {
            
            if (rootViewController.isKind(of: UITabBarController.self)) {
                let tabBarController = rootViewController as! UITabBarController
                
                if (tabBarController.selectedViewController!.isKind(of: UINavigationController.self)) {
                    let navigationController = tabBarController.selectedViewController as! UINavigationController
                    return navigationController.visibleViewController!
                } else {
                    return tabBarController.selectedViewController!
                }
            }
            
            if (rootViewController.isKind(of: UINavigationController.self)) {
                let navigationController = rootViewController as! UINavigationController
                return navigationController.visibleViewController!
            }
            
            if ((rootViewController.presentedViewController) != nil) {
                return rootViewController.presentedViewController!
            }
            
            return rootViewController
        }else{
            return nil
        }
    }
}
